<?php
use think\Response;
use think\Log;
use controller\Easemob;
use JPush\Client as JPush;

function buildToken($username)
{
	return md5(sha1(uniqid($username)) . config('token_key'));
}

// 短信验证码生成器
function randCode()
{
    $str = '';
    $arr=$return = array();
    $count1=$count = 0;
    while ($count < 6) 
    {
        $return[] = mt_rand(1, 9);
        $return = array_flip(array_flip($return));
        $count = count($return);
    } 

    $arr=array_values($return);// 获得数组的值 
    foreach($arr as $key)
    {
        $str .= $key;
    }
    return $str;
}

function GetfourStr($len) 
{ 
  $chars_array = array( 
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 
    "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", 
    "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
    "S", "T", "U", "V", "W", "X", "Y", "Z", 
  ); 
  $charsLen = count($chars_array) - 1; 
  
  $outputstr = ""; 
  for ($i=0; $i<$len; $i++) 
  { 
    $outputstr .= $chars_array[mt_rand(0, $charsLen)]; 
  } 
  return $outputstr; 
}

function count_days($a,$b){
    $a_dt = getdate($a);
    $b_dt = getdate($b);
    $a_new = mktime(12, 0, 0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
    $b_new = mktime(12, 0, 0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);
    return round(abs($a_new-$b_new)/86400);
} 

/**
 * 方法一: 获取指定日期段内每一天的日期
 * @date 2017-02-23 14:50:29
 *
 * @param $startdate
 * @param $enddate
 *
 * @return array
 */
function getDateRange($stime, $etime) {
    $datearr = [];
    while ($stime <= $etime) {
        $datearr[] = $stime;//得到dataarr的日期数组。
        $stime = $stime + 86400;
    }
    return $datearr;
}

/**
 * 生成二维码
 * @param  string  $url  url连接
 * @param  integer $size 尺寸 纯数字
 */
function qrcode($travel_id,$url,$size=8){
    Vendor('phpqrcode.phpqrcode');
    // 如果没有http 则添加
    if (strpos($url, 'http')===false) {
        $url= config('url_domain_root').$url;
    }

    $QRcode = new \QRcode();

    $img = 'uploads/qrcode/'.$travel_id.'.png';
    $QRcode->png($url, $img , QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000); 

    // 生成缩略图
    $images = config('url_domain_root').$img;

    return $images;
}

// 推送提醒
function jpush($type,$mobile,$msg)
{
    $client = new JPush(config('JPush.app_key'), config('JPush.master_secret'));
    $pusher = $client->push();
    $pusher->setPlatform('all');
   // $pusher->setPlatform('ios');
    //$pusher->addAlias(array('15052760816'));
    $pusher->addAlias(array($mobile));
    //$pusher->addTag(array('tag1', 'tag2'))
    //$pusher->addAllAudience();
    $pusher->setNotificationAlert($msg);

   // $pusher->send();
    try {
        $pusher->send();
    } catch (\JPush\Exceptions\JPushException $e) {
        // try something else here
        return 1;
       // exit;
    }

    $data['type'] = $type;
    $data['alias'] = $mobile;
    $data['msg'] = $msg;

    model('JpushData')->save($data);
    return 0;
}

function webhookjpush($type,$mobile,$msg)
{
    $client = new JPush(config('JPush.app_key'), config('JPush.master_secret'));
    $pusher = $client->push();
    $pusher->setPlatform('all');
   // $pusher->setPlatform('ios');
    //$pusher->addAlias(array('15052760816'));
    $pusher->addAlias(array($mobile));
    //$pusher->addTag(array('tag1', 'tag2'))
    //$pusher->addAllAudience();
    $pusher->setNotificationAlert($msg);

   // $pusher->send();
    try {
        $pusher->send();
    } catch (\JPush\Exceptions\JPushException $e) {
        // try something else here
        exit;
    }

    $data['type'] = $type;
    $data['alias'] = $mobile;
    $data['msg'] = $msg;

    model('JpushData')->save($data);
}

// type  用户类型：1 供应商；2 社群用户
// mode  0 收入；1 支出
function paylog($type,$user_id,$title,$content,$mode,$fee)
{
    $data = [
        'type'     => $type,
        'user_id'  => $user_id,
        'title'    => $title,
        'content'  => $content,
        'mode'     => $mode,
        'fee'      => $fee,
    ];
    model('Paylog')->save($data);
}


function getChatHistory()
{
    Log::info('获取聊天记录', 'begin');
    $h = new Easemob();
    // 定时任务（整点执行一次）通过接口获取聊天历史记录 url，执行url将历史记录包保存到指定目录下
    $ql = '2018011716';
    //$ql = date('YmdH',strtotime("-2 hour"));

    /*if(cache('history_url_'.$ql))
    {
        $history_url = cache('history_url_'.$ql);
        LogService::write('聊天记录'.$ql, '获取历史聊天记录url from cache：'.$history_url);
    }
    else
    {*/
        $result = $h->getChatRecord($ql);
        
        if(isset($result['error']))
        {
            Log::info('聊天记录'.$ql, '获取历史聊天记录url from interface失败：'.$result['error']);
        }

        $history_url = $result['data'][0]['url'];
        cache('history_url_'.$ql, $history_url);
        Log::info('聊天记录'.$ql, '获取历史聊天记录url from interface: '.$history_url);
   // }
        //var_dump($history_url);exit;
    $new_file = dirname(dirname(__DIR__)).'/public/uploads/chat/'.$ql.'.gz';
   // $new_file = config('url_domain_root').'uploads/chat/'.$ql.'.gz';
    $result   = copy($history_url, $new_file);
    if ($result == false)
    {
        Log::info('聊天记录', '复制失败');
        echo '复制失败';exit;
    }

    return readChat($new_file);
}

function readChat($new_file)
{
    $buffer_size = 4096; // read 4kb at a time
    $out_file_name = str_replace('.gz', '', $new_file);
    // Open our files (in binary mode)
    $file = gzopen($new_file, 'rb');
    $out_file = fopen($out_file_name, 'wb');

    while(!gzeof($file))
    {
        fwrite($out_file, gzread($file, $buffer_size));
    }

    fclose($out_file);
    gzclose($file);

    $file = fopen($out_file_name, "r");
    $list = [];
    $i=0;
    //输出文本中所有的行，直到文件结束为止。
    while(!feof($file))
    {
        $list[$i]=json_decode(fgets($file),true);//fgets()函数从文件指针中读取一行
        $i++;
    }

    fclose($file);
    $list=array_filter($list);

    Log::info('聊天记录', '记录行数：'.count($list));

    return $list;
}

function build_sn($address)
{
    //API控制台申请得到的ak（此处ak值仅供验证参考使用）
    $ak = 'Qblrt1BGVDYFUBho94vE2isqMrfT2fxZ';

    //应用类型为for server, 请求校验方式为sn校验方式时，系统会自动生成sk，可以在应用配置-设置中选择Security Key显示进行查看（此处sk值仅供验证参考使用）
    $sk = 'nGajvBxqbwLYk4OqL2s2jcLTBmNGzk8z';

    //以Geocoding服务为例，地理编码的请求url，参数待填
    $url = "http://api.map.baidu.com/geocoder/v2/?address=%s&output=%s&ak=%s&sn=%s";

    //get请求uri前缀
    $uri = '/geocoder/v2/';

    //地理编码的请求中address参数
   // $address = '百度大厦';

    //地理编码的请求output参数
    $output = 'json';

    //构造请求串数组
    $querystring_arrays = [
        'address' => $address,
        'output' => $output,
        'ak' => $ak
    ];

    //调用sn计算函数，默认get请求
    $sn = caculateAKSN($ak, $sk, $uri, $querystring_arrays);

    //请求参数中有中文、特殊字符等需要进行urlencode，确保请求串与sn对应
    $target = sprintf($url, urlencode($address), $output, $ak, $sn);

    $result = postCurl($target,'get');
    if($result['status'] == 0)
    {
        return $result['result']['location'];
    }
    return ['lng'=>null,'lat'=>null];
}

function caculateAKSN($ak, $sk, $url, $querystring_arrays, $method = 'GET')
{  
    if ($method === 'POST'){  
        ksort($querystring_arrays);  
    }  
    $querystring = http_build_query($querystring_arrays);  
    return md5(urlencode($url.'?'.$querystring.$sk));  
}
/**
 *$this->postCurl方法
 */
function postCurl($url,$type="POST"){
    //1.创建一个curl资源
    $ch = curl_init();
    //2.设置URL和相应的选项
    curl_setopt($ch,CURLOPT_URL,$url);//设置url
    //1)设置请求头
    //array_push($header, 'Accept:application/json');
    //array_push($header,'Content-Type:application/json');
    //array_push($header, 'http:multipart/form-data');
    //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
    curl_setopt($ch,CURLOPT_HEADER,0);
//      curl_setopt ( $ch, CURLOPT_TIMEOUT,5); // 设置超时限制防止死循环
    //设置发起连接前的等待时间，如果设置为0，则无限等待。
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //上传文件相关设置
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算
    
    //3)设置提交方式
    switch($type){
        case "GET":
            curl_setopt($ch,CURLOPT_HTTPGET,true);
            break;
        case "POST":
            curl_setopt($ch,CURLOPT_POST,true);
            break;
        case "PUT"://使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。这对于执行"DELETE" 或者其他更隐蔽的HTT
            curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"PUT");
            break;
        case "DELETE":
            curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"DELETE");
            break;
    }
    
    //4)在HTTP请求中包含一个"User-Agent: "头的字符串。-----必设

//      curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
//      curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

    curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
    //5)
    
    //3.抓取URL并把它传递给浏览器
    $res=curl_exec($ch);


    $result=json_decode($res,true);
    //4.关闭curl资源，并且释放系统资源
    curl_close($ch);
    if(empty($result))
        return $res;
    else
        return $result;
}

function getLastSexMonth()
{
    $return = [];
    for ($i=0; $i < 6; $i++) { 
        array_push($return, strtotime('-'.$i.' month',time()));
    }
    return $return;
}

function getthemonth($date) 
{ 
    $firstday = date('Y-m-01', strtotime($date)); 
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day")); 
    return array($firstday, $lastday); 
} 

function gettheweek() 
{
    $return = [];
    array_push($return, time());
    array_push($return, strtotime('-6 day',time()));
    /*for ($i=0; $i < 7; $i++) { 
        array_push($return, strtotime('-'.$i.' day',time()));
    }*/
    return $return;
} 

function getNextDistance($origins,$destinations)
{
    $send_url = "http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=$origins&destinations=$destinations&ak=Qblrt1BGVDYFUBho94vE2isqMrfT2fxZ";
    $result = postCurl($send_url,'get');
    if($result['status'] == 0)
    {
        return $result['result'][0]['distance']['text'];
    }
    return 0;
}

function orderByAddtime($travelList)
{
    $flag = array();  
    foreach($travelList as $v)
    {  
        $flag[] = $v['createtime'];  
    } 

    array_multisort($flag, SORT_DESC, $travelList);  
   // $travelList = array_slice($travelList,0,3);
    return $travelList;
}

function str_insert($str, $i, $substr) 
{     
    $startstr=$laststr= '';
    //通过遍历获取字符串的前半部分
    for($j=0; $j<$i; $j++){ 
        $startstr .= $str[$j]; 
    } 
    //通过遍历获取字符串的后半部分
    for ($j=$i; $j<strlen($str); $j++){ 
        $laststr .= $str[$j]; 
    } 
//字符串重新组装
$str = ($startstr . $substr . $laststr); 
return $str; 
}
function afterStr($origiStr, $n, $str, $encoding='utf-8'){
    $part1 = mb_substr($origiStr, 0,  $n,   $encoding);
    $part2 = mb_substr($origiStr, $n, NULL, $encoding);
    return $part1.$str.$part2;
}

function getBankAbbr($cardNo)
{
    //$cardNo = "6212261102031461281";
    $url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=$cardNo&cardBinCheck=true";
    $result = postCurl($url,'get');
    if($result['stat'] == 'ok')
    {
        return $result['bank'];
    }
    return 'QTB';
}

/**
*  支付验证
*  $channel   交易渠道
*  $transpwd  交易密码
*/
function valiPayment($valiParam)
{
    $code = 0;
    $channel = $valiParam['channel'];
    $transpwd = $valiParam['transpwd'];
    // 查询认证信息：绑定银行卡、交易密码
    // type 用户类型 1 供应商；2、社群|用户
    $realAuth = model('realAuth')->get(['type'=>$valiParam['type'],'user_id'=>$valiParam['user']['id']]);
    // 查看交易类型是否需要验证交易密码
    if(in_array($channel,config('payNeedTranpwd')))
    {
        // 银联支付 没有绑定银行卡提示
        if($channel == 'UN_APP' && !$realAuth['card_no']) $code = 412;
        // 验证交易密码
        if(valiTranspwd($realAuth,$transpwd)) $code = valiTranspwd($realAuth,$transpwd);
        // 余额支付 判断余额是否充足
        if($channel == 'YE_APP' && $valiParam['user']['wallet_money'] < $valiParam['payfee']) $code = 10; 
    }
    return $code;
}

/**
*  验证交易密码
*  $channel   交易渠道
*  $transpwd  交易密码
*/
function valiTranspwd($realAuth,$transpwd)
{
    $code = 0;
    $realAuthModel = model("realAuth");
    if(empty($transpwd)) $code = 407;
    //禁止登陆开始时间存在，并且距离目前时间大于24小时，则errortime和errorcount清空
    if($realAuth['errortime'])
    {
        // 交易密码输错次数大于允许的最大字数
        if($realAuth['errorcount'] > config('transpwd_error_limit')) $code = 415;

        if((time() - $realAuth['errortime']) > 3600*24)
        {
            $realAuthModel->save(['errortime'=>0,'errorcount'=>0],['id'=>$realAuth['id']]);
        }
    }

    if(!password_verify($transpwd, $realAuth['transpwd']))
    {
        // 交易密码失败，查看errortime是否为零
        $errorData['errortime'] = empty($realAuth['errortime'])?time():$realAuth['errortime'];
        $errorData['errorcount'] = $realAuth['errorcount'] + 1;
        $realAuthModel->save($errorData,['id'=>$realAuth['id']]);
        $code = 413;
    }
    // 交易密码输入成功，重置errortime和errorcount
    $realAuthModel->save(['errortime'=>0,'errorcount'=>0],['id'=>$realAuth['id']]);
    return $code;
}

